import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { type } from 'os';
import { TagService } from 'src/tag/tag.service';
import { TypeService } from 'src/type/type.service';
import { UserService } from 'src/user/user.service';
import { Repository } from 'typeorm';
import { Blog } from './blog.entity';
import { BlogDto } from './dto/blog.dto';

const path = require("path");
const fs = require('fs')

@Injectable()
export class BlogService {
    constructor(
        @InjectRepository(Blog)
        private readonly blogRepo: Repository<Blog>,
        private readonly typeService: TypeService,
        private readonly tagService: TagService,
        private readonly userService: UserService
    ) { }

    async saveBlog(newBlog: BlogDto, userId: number) {
        const addedBlog = new BlogDto()
        addedBlog.userId = userId
        addedBlog.user = await this.userService.getUserById(userId)
        addedBlog.title = newBlog.title
        addedBlog.introduction = newBlog.introduction
        addedBlog.firstPicture = newBlog.firstPicture
        addedBlog.views = newBlog.views
        addedBlog.content = newBlog.content
        addedBlog.typeId = newBlog.typeId
        addedBlog.type = await this.typeService.getTypeById(newBlog.typeId)
        addedBlog.tags = await this.tagService.getTagsByIds(newBlog.tagIds)
        // console.log(addedBlog)
        // 将markdown保存为单独的文件
        var upLoadPath = path.join(__dirname, '../../public/Blog/');
        fs.writeFile(upLoadPath + `${newBlog.title}.md`, newBlog.content, error => {
            if (error) console.log(error)
        })
        //console.log(addedBlog)
        return await this.blogRepo.save(addedBlog)
    }

    async getAllBlogs() {
        return await this.blogRepo.find({ relations: ['type', 'tags', 'user'] })
    }

    async getBlogById(id) {
        return await this.blogRepo.findOne(id, { relations: ['type', 'tags', 'user'] })
    }

    // 分页返回数据 包括 totalnum 、pagenum、tags
    async getBlogsByQuery(query, pagenum, pagesize, orderBy?: string, typeId?: number) {
        let keyWord1 = { key: `%${query}%` }
        let keyWord2 = { type: `${typeId}` }
        let sql1 = query ? 'blog.title like :key' : "1=1"
        let sql2 = typeId ? 'blog.typeId = :type' : "1=1"

        let orderByParm = {}
        if(orderBy){
            orderByParm[orderBy] = 'DESC'
        }

        let blogs = await this.blogRepo
            .createQueryBuilder('blog')
            .leftJoinAndSelect('blog.user', 'author')
            .leftJoinAndSelect('blog.type', 'typeName')
            .leftJoinAndSelect('blog.tags', 'tagNames')
            //.where("tag.name like :name", {name: `%${query}%`})
            .where(sql1, keyWord1)
            .andWhere(sql2, keyWord2)
            .skip((pagenum - 1) * pagesize)
            .take(pagesize)
            .orderBy(orderByParm)
            .getManyAndCount()
        // console.log(tags)
        let total = blogs[1]
        // 整理结果
        let result = {
            total: total,
            pagenum: pagenum,
            blogs: blogs[0]
        }

        return result
    }

    // 更新博客
    async updateBlog(id, updatedBlog: BlogDto, userId: number) {
        const updatedData = await this.getBlogById(id)
        //updatedData.userId = userId
        updatedData.user = await this.userService.getUserById(userId)
        updatedData.title = updatedBlog.title
        updatedData.introduction = updatedBlog.introduction
        updatedData.firstPicture = updatedBlog.firstPicture
        updatedData.views = updatedBlog.views
        updatedData.content = updatedBlog.content
        console.log(updatedBlog.content)
        //updatedData.typeId = updatedBlog.typeId
        updatedData.type = await this.typeService.getTypeById(updatedBlog.typeId)
        updatedData.tags = await this.tagService.getTagsByIds(updatedBlog.tagIds)
        // 将markdown保存为单独的文件
        var upLoadPath = path.join(__dirname, '../../public/Blog/');
        fs.writeFile(upLoadPath + `${updatedData.title}.md`, updatedData.content, error => {
            if (error) console.log(error)
        })
        //console.log(updatedData)
        return await this.blogRepo.save(updatedData)
    }

    // 删除博客
    async deleteBlog(id){
        return await this.blogRepo.delete(id)
    }
}
